package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.Admin;
import com.xmy.cultivate.entity.Staff;
import com.xmy.cultivate.enums.StatusStaffEnum;
import com.xmy.cultivate.mapper.AdminMapper;
import com.xmy.cultivate.service.IAdminService;
import com.xmy.cultivate.service.IAliyunApiService;
import com.xmy.cultivate.service.IStaffService;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.Result;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/api/password")
public class retrievePasswordController extends BaseController{

//    @Resource
//    AdminMapper adminMapper;

    @Autowired
    IAliyunApiService iAliyunApiService;

    @Autowired
    IStaffService iStaffService;

    @Autowired
    IAdminService iAdminService;

    /**
     * 发送短信验证码
     * @param phone
     * @return
     */
    @GetMapping("/sendCommonVerifyCode")
    public Result sendCommonVerifyCode(@RequestParam("phone") String phone){
        //去掉空格
        phone = phone.replace(" ","");
        if(phone.length() != 11){
            return new Result(Code.ERROR,"","手机号格式不正确，请检查手机号是否正常");
        }
        QueryWrapper<Staff> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
//        queryWrapper.eq("status",1);
        queryWrapper.last("LIMIT 1");
        Staff staff = iStaffService.getOne(queryWrapper);
        if(staff == null){
            return new Result(Code.ERROR,"","该手机号未录入企业，请联系管理员");
        }
        if (staff.getStatus().equals(StatusStaffEnum.OUT)){
            return new Result(Code.ERROR,"","已离职，不能登录");

        }
        iAliyunApiService.sendCommonVerifyCode(phone);
        return new Result(Code.OK,"","验证码发送成功，有效时间1分钟");
    }

    /**
     * 验证短信验证码
     * @param phone
     * @param code
     * @return
     */
    @GetMapping("/verifyCommonCode")
    public Result verifyCommonCode( @RequestParam("phone") String phone,@RequestParam("code") String code){

        boolean verifyCommonCode = iAliyunApiService.verifyCommonCode(phone, code);
        if (!verifyCommonCode) {
            return new Result(Code.ERROR, null, "验证码错误");
        }
        return new Result(Code.OK,null,"验证码验证成功");

    }

    /**
     * 获取账号信息
     * @param phone
     * @return
     */
    @GetMapping("/accountInfo")
    public Result accountInfo(@RequestParam("phone") String phone){
        QueryWrapper<Staff> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
//        queryWrapper.eq("status",1);
        queryWrapper.last("LIMIT 1");
        Staff staff = iStaffService.getOne(queryWrapper);
        if(staff == null){
            return new Result(Code.ERROR,"","该手机号未录入企业，请联系管理员");
        }
        if (staff.getStatus().equals(StatusStaffEnum.OUT)){
            return new Result(Code.ERROR,"","已离职，不能登录");

        }
        QueryWrapper<Admin> queryWrapperAdmin = new QueryWrapper<>();
        queryWrapperAdmin.eq("id",staff.getId());
        queryWrapperAdmin.last("LIMIT 1");
        Admin admin = iAdminService.getOne(queryWrapperAdmin);
        if (admin == null){
            return new Result(Code.ERROR,"","该账号不存在");
        }
        return new Result(Code.OK,admin,Code.GET_OK_MSG);

    }

    @PostMapping(value = "/densification")
    @ApiOperation("忘记密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名", required = true, dataType = "String"),
            @ApiImplicitParam(name = "passwordNew", value = "想修改的密码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "passwordNext", value = "再次输入密码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "id", value = "账号id", required = true, dataType = "String")
    })
    public Result Densification(@RequestBody Map<String, Object> reMap) {
        /**
         * 密码加密：
         *     shiro提供的md5加密
         *     Md5Hash:
         *      参数一：加密的内容
         *              111111   --- abcd
         *      参数二：盐（加密的混淆字符串）（用户登录的用户名）
         *              111111+混淆字符串
         *      参数三：加密次数
         */

        String passwordNew = (String) reMap.get("passwordNew");
        String passwordNext = (String) reMap.get("passwordNext");
        String id = (String) reMap.get("id");

        if (StringUtils.isEmpty(passwordNew) || StringUtils.isEmpty(passwordNext)) {
            return new Result(Code.ERROR, null, "密码不能为空");
        }

        Admin admin = iAdminService.getById(id);
        if (admin == null) {
            return new Result(Code.ERROR, null, "当前用户不存在,数据异常!");
        }

        if (!passwordNext.equals(passwordNew)) {
            return new Result(Code.ERROR, null, "两次输入密码不一致！");
        }

        if (Objects.equals(admin, null)) {
            return new Result(Code.ERROR, null, "当前用户不存在,数据异常!");
        }


        String passwordMd5 = new Md5Hash(passwordNew, admin.getAccount(), 3).toString();
        admin.setPwd(passwordMd5);
        admin.setPwdShow(passwordNew);
        boolean update = iAdminService.updateById(admin);
        if (!update) {
            return new Result(Code.ERROR, null, "密码设置失败！");
        }
        return new Result(Code.OK, null, "密码设置成功~");
    }


}
